package cn.com.gps169.jt808.tool;

import cn.com.gps169.db.model.GpsInfo;
import net.sf.json.JSONObject;

/**
 * 位置信息工具类
 * @author tianfei
 *
 */
public class GpsTool {
	
	private static final String KEY = "bf31d04b21343326cf24de7df104a675";
	//www.che08.com/gis/ws/0.1/simplegeocoding?lat=39.990475&lon=116.481499&range&pattern&serviceid=1&encoded=0
	//www.che08.com/gis/ws/0.1/gps/encode?latlon=116.456451%2C40.022356&serviceid=1
	
	/**
	 * 将GPS偏转为高德位置 
	 * @param gpsInfo
	 * @return
	 */
	public static GpsInfo deflectGpsData(GpsInfo gpsInfo) { 
		String url = "http://restapi.amap.com/v3/assistant/coordinate/convert";
		JSONObject params = new JSONObject();
		params.put("locations", gpsInfo.getLongitude()+","+gpsInfo.getLatitude());
		params.put("coordsys", "gps");
		params.put("output", "json");
		params.put("key", KEY);
		JSONObject result = RestfulInvokeService.getData(url, params);
		if(result != null && "1".equals(result.get("status"))){
			String[] str = result.opt("locations").toString().split(",");
			gpsInfo.setLongitude(Double.parseDouble(str[0]));
			gpsInfo.setLatitude(Double.parseDouble(str[1]));
			gpsInfo.setLocation(deflectGps(gpsInfo.getLongitude(), gpsInfo.getLatitude()));
			return gpsInfo;
		}
		
		return gpsInfo;
	}
	
	/**
	 * 逆地址解析
	 * @param longitude
	 * @param latitude
	 * @return
	 */
	public static String deflectGps(double longitude,double latitude) {
		String url = "http://restapi.amap.com/v3/geocode/regeo";
		JSONObject params = new JSONObject();
		params.put("location", longitude+","+ latitude);
		params.put("key", KEY);
		JSONObject result = RestfulInvokeService.getData(url, params);
		if(result != null && "1".equals(result.getString("status"))){
			JSONObject regeocode = result.optJSONObject("regeocode");
			JSONObject streetNumber = regeocode.optJSONObject("addressComponent").getJSONObject("streetNumber");
			if(streetNumber.optString("direction").equals("[]")){
				return regeocode.optString("formatted_address");
			}else{
				return regeocode.optString("formatted_address") + streetNumber.optString("street") + streetNumber.optString("number") + streetNumber.optString("direction")+streetNumber.optInt("distance")+"米";
			}

		}
		return "未知";
	}
	
	public static void main(String[] args){
		GpsInfo g = new GpsInfo();
		g.setLongitude(116.481499);
		g.setLatitude(39.990475);
//
		g = deflectGpsData(g);
		System.out.println(g.getLongitude() + "  "+g.getLatitude());
		System.out.println(g.getLocation());

		System.out.println(deflectGps(114.814007161459,36.374153645834));
	}

}
